package com.ysccc.shares.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.ysccc.shares.entity.Shares;
import com.ysccc.shares.entity.SharesDaily;
import com.ysccc.shares.manager.SharesDailyManager;
import com.ysccc.shares.manager.SharesManager;
import com.ysccc.shares.web.vo.SharesDailyPageVo;
import com.ysccc.spring.boot.starter.sqldb.repository.support.FilterParam;
import com.ysccc.spring.boot.starter.sqldb.repository.support.FilterParam.Operator;
import com.ysccc.spring.boot.starter.sqldb.repository.support.FilterParamBuilder;
import com.ysccc.spring.boot.starter.sqldb.repository.support.JpaSorts;
import com.ysccc.spring.boot.starter.web.commons.builder.JsonBuilder;
import com.ysccc.spring.boot.starter.web.commons.builder.JsonBuilder.JsonList;
import com.ysccc.tools.Converts;
import com.ysccc.tools.Emptys;

@RestController
@RequestMapping("/shares/daily")
public class SharesDailyController {
	
	@Autowired
	private SharesManager sharesManager;

	@Autowired
	private SharesDailyManager sharesDailyManager;

	@PostMapping("/page")
	public JsonList page(HttpServletRequest request) {
		List<FilterParam> params = Lists.newArrayList();
		List<SharesDailyPageVo> vos = Lists.newArrayList();
		String sharesId = request.getParameter("sharesId");
		if (Emptys.isNotEmpty(sharesId)) {
			params.add(new FilterParam("id", sharesId, Operator.EQ));
		}
		int page = Converts.toInt(request.getParameter("page"));
		int size = Converts.toInt(request.getParameter("size"));
		if (size == 0) {
			size = 10;
		}
		List<Shares> shareses = sharesManager.findList(params);
		if (Emptys.isNotEmpty(shareses)) {
			for (Shares shares : shareses) {
				Page<SharesDaily> daily = sharesDailyManager.findPage(
						FilterParamBuilder.create().eq("shares.id", shares.getId()).build(),
						PageRequest.of(page, size, JpaSorts.desc("day"))
				);
				SharesDailyPageVo vo = new SharesDailyPageVo(shares, daily);
				vos.add(vo);
			}
		}
		return JsonBuilder.of(vos).build(JsonList.class);
	}
}
